package com.code.day04_utiles;

import com.code.day04_utiles.pojo.Category;
import com.code.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;


//DBUtils 的四种查询

public class Demo04DBUtils {


    //只会输出符合条件的第一条,建议加上where 条件
    @Test
    public void BeanHandler() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        String sql="select * from category where id=?";
        Category category = queryRunner.query(sql,new BeanHandler<Category>(Category.class),1);
        System.out.println(category);

    }

    @Test
    public void BeanListHandler() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        String sql="select * from category limit 5";
        List<Category> category = queryRunner.query(sql,new BeanListHandler<Category>(Category.class));
        for (Category category1 : category) {
            System.out.println(category1);
        }

    }

    //比较适合聚合函数
    @Test
    public void ScalarHandler() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        String sql="select count(1) from category";
        Object o = queryRunner.query(sql,new ScalarHandler<>()); //要用java lang
        System.out.println(o);

    }

    @Test
    public void columnListHandler() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
        String sql="select * from category limit 5";
        List<Object> category = queryRunner.query(sql,new ColumnListHandler<>("cname"));
        System.out.println(category); //[蔬菜, java0, java1, java2, java3]


    }


}
